package com.ygkj.common.distributionlock.mysql;

import com.ygkj.common.distributionlock.lock.AbstractLock;

import javax.annotation.Resource;

public class MysqlLock extends AbstractLock {
    @Resource
    private LockMapper mapper;

    //所有的线程都往数据库插入主键值相同的数据
    private static final int LOCK_ID = 1;

    /**
     * non block get lock
     * @return boolean
     */
    public boolean tryLock() {
        try {
            mapper.lock(LOCK_ID);
        } catch (Exception e) {
            return false;
        }
        return true;
    }

    /**
     * current thread wait moment
     */
    public void waitLock() {
        try {
            Thread.currentThread().sleep(10);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    /**
     * release lock
     */
    public void unLock() {
        mapper.unLock(LOCK_ID);
    }
}
